package com.example.shirodemo.demos.shiro;

import com.example.shirodemo.demos.dao.UserDAO;
import com.example.shirodemo.demos.entity.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;

//@Component
public class MyRealm extends AuthorizingRealm {

    @Resource
    private UserDAO userDAO;

    @Override
    public String getName() {
        return "myRealm";
    }

    /**
     * 获取授权信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();

        // 根据用户名查询该用户的所有角色和权限
        List<String> roles = userDAO.findRoleByUsername(username);
        roles.add("admin");
        List<String> permissions = userDAO.findPermissionByUsername(username);
        permissions.add("user:list");

        // 返回当前用户所有角色和权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);

        return info;
    }

    /**
     * 获取认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取当前用户的用户名
        String username = (String) authenticationToken.getPrincipal();
        // 去数据库中查询用户
        User user = userDAO.getUserByUsername(username);
        if (user == null) {
            return null;
        }
        String salt = "abcdefg";
        return new SimpleAuthenticationInfo(username, user.getPassword(), ByteSource.Util.bytes(salt), getName());
    }
}
